using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace ImageResizeConsole
{
    class ImageResize
    {
        static void Main(string[] args)
        {
            //set a working directories
            if (args.Length == 1)
            {
                string WorkingDirectory = args[0];

                string[] files = Directory.GetFiles(WorkingDirectory, "*.jpg", SearchOption.AllDirectories);
                foreach (string file in files)
                {
                    try
                    {
                        Image imgPhotoOrig = Image.FromFile(file);
                        // only handle those who are in landscape mode
                        if (imgPhotoOrig.Width >= imgPhotoOrig.Height)
                        {
                            Image imgPhoto = null;

                            imgPhoto = ScaleByFixedSize(imgPhotoOrig, 800, 480);
                            imgPhotoOrig.Dispose();
                            imgPhoto.Save(file, ImageFormat.Jpeg);
                            imgPhoto.Dispose();
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine("Exception: " + e.Message);
                    }
                }
            }
            else
                Console.WriteLine("ImageResizeConsole.exe \"Directory\"");
        }

        #region Drawing Impl

        static Image ScaleByFixedSize(Image imgPhoto, int Width, int Height)
        {
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;

            int destX = 0;
            int destY = 0;
            int destWidth = Width;
            int destHeight = Height;

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                              new Rectangle(destX, destY, destWidth, destHeight),
                              new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                              GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }

        #endregion

    }
}
